from django.http import JsonResponse
import json
from ..models import Notice
from django.core.paginator import Paginator
from django.db.models import Q
import django.utils.timezone as timezone


def notice_handle(request):
    if request.method == 'GET':
        request.params = request.GET
    else:
        request.params = json.loads(request.body)
    action = request.params.get('action')

    if action in action_handler_dict_mg:
        if not request.user.is_authenticated:
            return JsonResponse({'ret': 1, 'msg': '未登录'}, json_dumps_params={'ensure_ascii': False})
        if request.user.usertype not in [1, 1000]:
            return JsonResponse({'ret': 1, 'msg': '非管理员'}, json_dumps_params={'ensure_ascii': False})
        return action_handler_dict_mg[action](request)
    elif action in action_handler_dict_all:
        return action_handler_dict_all[action](request)
    else:
        return JsonResponse({'ret': 1, 'msg': 'action参数错误'})

def listbypage(request):
    try:
        withoutcontent=request.params.get('withoutcontent')
        if withoutcontent:
            qs = Notice.objects.filter(status=1).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'status').order_by('-pubdate')
        else:
            qs = Notice.objects.filter(status=1).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'content', 'status').order_by('-pubdate')

        pagesize = request.params.get('pagesize')
        pagenum = request.params.get('pagenum')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(title__contains=k)
            qs = qs.filter(query)
        pgnt = Paginator(qs, pagesize)
        page = pgnt.get_page(pagenum)
        items = list(page)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'total': pgnt.count,
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def listbypage_allstate(request):
    try:
        withoutcontent=request.params.get('withoutcontent')
        if withoutcontent:
            qs = Notice.objects.values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'status').order_by('-pubdate')
        else:
            qs = Notice.objects.values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'content', 'status').order_by('-pubdate')

        pagesize = request.params.get('pagesize')
        pagenum = request.params.get('pagenum')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(title__contains=k)
            qs = qs.filter(query)
        pgnt = Paginator(qs, pagesize)
        page = pgnt.get_page(pagenum)
        items = list(page)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'total': pgnt.count,
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def getone(request):
    try:
        noticeid = request.params.get('id')
        rec = Notice.objects.filter(id=noticeid).values(
        'id', 'pubdate', 'author', 'author__realname', 
        'title', 'content', 'status')[0]
        if rec.get('status') != 1 and request.user.usertype not in [1, 1000]:
            return JsonResponse({'ret': 1, 'msg': '权限不足'})
        return JsonResponse(
            {
                'ret': 0, 
                'rec': rec,
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def addone(request):
    try:
        data = request.params['data']
        data['author'] = request.user
        record = Notice.objects.create(**data)
        return JsonResponse({'ret': 0, 'id': record.id})
    except Exception as e:
        return JsonResponse(
            {'ret': 1, 'msg': str(e)})

def modifyone(request):
    try:
        noticeid = request.params['id']
        newdata = request.params['newdata']
        newdata['modidate'] = timezone.now()
        Notice.objects.filter(id=noticeid).update(**newdata)
        return JsonResponse({'ret': 0})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def banone(request):
    try:
        noticeid = request.params['id']
        notice = Notice.objects.filter(id=noticeid)
        notice.update(status=3)
        return JsonResponse({'ret': 0, 'status':f'{notice[0].status}'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def publishone(request):
    try:
        noticeid = request.params['id']
        notice = Notice.objects.filter(id=noticeid)
        notice.update(status=1)
        return JsonResponse({'ret': 0, 'status':f'{notice[0].status}'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def deleteone(request):
    try:
        noticeid = request.params['id']
        Notice.objects.get(id=noticeid).delete()
        return JsonResponse({'ret': 0})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})


action_handler_dict_mg = {
    'listbypage_allstate': listbypage_allstate,
    'addone': addone,
    'modifyone': modifyone,
    'banone': banone,
    'publishone': publishone,
    'deleteone': deleteone,
}

action_handler_dict_all = {
    'listbypage': listbypage,
    'getone': getone,
}